package com.jd.dlc.limit.biz;

import com.jd.dlc.domain.WrapLimiterRule;
import com.jd.dlc.limit.cache.LimiterRecord;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @program: dlc
 * @ClassName PreCheck
 * @description:
 * @author: sizegang
 * @create: 2022-06-11
 **/
@Slf4j
@Component
public class PreCheck {

    @Resource
    private LimiterRecord limiterRecord;


    public LimiterBencher onDo(Object[] args, WrapLimiterRule wrapLimiterRule) {
        Object arg = args[0];

        /**
         * only for dlc 2.0
         */
        if (!(arg instanceof LimiterBencher)) {
            log.error(" one parameter is no LimiterBencher!");
            return  new LimiterBencher().setCheckAssert(true).setAllowed(true);
        }
        LimiterBencher bencher = (LimiterBencher) arg;

        /**
         * 结算 pin 商详 SKU
         */
        if (wrapLimiterRule.getWhiteList() != null && wrapLimiterRule.getWhiteList().contains(bencher.getRecordKey())) {
            return new LimiterBencher().setPassAll(true);
        }

        if (wrapLimiterRule.getBlackList() != null && wrapLimiterRule.getBlackList().contains(bencher.getRecordKey())) {
            return new LimiterBencher().setForbidden(true);
        }

        /*
         * 自动黑名单是否开启
         */
        if (!wrapLimiterRule.isRecordLimit()) {
            return doing(bencher, true);
        }

        /**
         * Prevent wrong settings
         */
        if (bencher.isCheckAssert()) {
            bencher.setCheckAssert(false);
        }

        if (limiterRecord.isLimitRecord(wrapLimiterRule,bencher.getRecordKey())) {
            return doing(bencher, false);
        }
        /**
         * pass
         */
        return doing(bencher, true);
    }

    private LimiterBencher doing(LimiterBencher bencher, boolean b) {
        bencher.setCheckAssert(b);
        bencher.setAllowed(true); // Filtering will be done later
        return bencher;
    }
}
